﻿using Brc_PaaS.Common.Helper;
using Brc_PaaS.Common.Model.Basic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Brc_PaaS.Api.Filters
{
    public class LoginValidatorFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var controllerActionDesc = context.ActionDescriptor as ControllerActionDescriptor;
            var isExemption = controllerActionDesc.MethodInfo.GetCustomAttributes(inherit: true).Any(a => a.GetType().Equals(typeof(IgnorLoginValidatorAuth)));
            //如果没有被打上豁免标记，将需要进行登录验证
            if (!isExemption)
            {
                BaseResponseModel model = new BaseResponseModel() { IsSuccess = false, Msg = String.Empty };
                if (!context.HttpContext.Request.Headers.ContainsKey("UserToken"))
                {
                    model.Msg = "请求格式有误，请检查请求报文";
                    context.Result = new JsonResult(model);
                    return;
                }
                try
                {
                    var userToken = context.HttpContext.Request.Headers["UserToken"];
                    string playload = string.Empty;
                    string message = string.Empty;
                    bool isValidted = JwtHelper.ValidateJWT(userToken,out playload,out message);
                    if(!isValidted) //没有验证成功
                    {
                        model.Msg = message;
                        context.Result = new JsonResult(model);
                        return;
                    }

                    var dicPlayload=JsonHelper.DeserializeObject<Dictionary<string, object>>(playload);
                    var accountId = dicPlayload.First(x => x.Key == "accountid").Value.ToString();
                    if(string.IsNullOrWhiteSpace(accountId))
                    {
                        model.Msg = "账号信息有误，请检查";
                        context.Result = new JsonResult(model);
                        return;
                    }

                    context.HttpContext.Items.Add("AccountId",accountId );

                }
                catch (Exception ex)
                {
                    model.Msg = ex.Message;
                    context.Result = new JsonResult(model);
                }



            }
        }
    }

    /// <summary>
    /// 豁免登录不验证
    /// </summary>
    public class IgnorLoginValidatorAuth : Attribute, IFilterMetadata
    {

    }
}
